package com.starbucks.opencase.tool;

import com.starbucks.opencase.entity.entUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class toolUserInfo {
    @Autowired
    private JdbcTemplate con;

    /**
     * 随机抽一个商人
     * @return
     */
    public String randomBusinessman(String uid){
        try {
            return con.queryForObject("select uid from user_info where identity=1 and uid!=? order by rand() limit 1", String.class,uid);
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 随机抽一个玩家
     * @return
     */
    public String randomPlayer(String uid){
        try {
            return con.queryForObject("select uid from user_info where uid!=? order by rand() limit 1", String.class,uid);
        }catch (Exception e){
            return "";
        }
    }
    /**
     * 查询用户昵称
     * @param uid
     * @return
     */
    public String queryNicknameOfUID(String uid){
        return con.queryForObject("select nickname from user_info where uid=?", String.class,uid);
    }
    public boolean changeIdentity(String uid){
        return con.update("update user_info set identity=? where uid=?",queryIdentity(uid)==0?1:0,uid)>0;
    }
    public int queryIdentity(String uid){
        return con.queryForObject("select identity from user_info where uid=?", Integer.class,uid);
    }

    /**
     * 查询指定页的内容
     * @param nickname
     * @param nowPageNum
     * @return
     */
    public List<entUserInfo> queryList(String nickname,int nowPageNum){
        return con.query("select * from user_info where nickname like '%"+nickname+"%' limit ?,?",new BeanPropertyRowMapper<>(entUserInfo.class),(nowPageNum-1)*30,30);
    }

    /**
     * 查询页数
     * 每页30条
     * @param nickname
     * @return
     */
    public int queryAllPageNum(String nickname){
        int n=con.queryForObject("select count(*) from user_info where nickname like '%"+nickname+"%'",Integer.class);
        return n/30+(n%30==0?0:1);
    }
    public entUserInfo queryInfo(String uid){
        List<entUserInfo> as=con.query("select * from user_info where uid=?",new BeanPropertyRowMapper<>(entUserInfo.class),uid);
        if(as.isEmpty())return null;
        return as.get(0);
    }
}
